#!/usr/bin/env python3
import os
import time
import subprocess
import logging
import threading

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('/var/log/app.log'),
        logging.StreamHandler()
    ]
)

class SDMonitor:
    def __init__(self):
        self.device = "/dev/mmcblk1p3"
        self.mount_point = "/media/sdcard"
        self.running = False
        
        # 创建挂载点
        if not os.path.exists(self.mount_point):
            os.makedirs(self.mount_point, mode=0o755)
            logging.info(f"创建挂载点: {self.mount_point}")
    
    def check_device(self):
        """检查设备是否存在"""
        return os.path.exists(self.device)
    
    def mount_device(self):
        """挂载设备"""
        try:
            result = subprocess.run(['mount', self.device, self.mount_point], 
                                  capture_output=True, text=True)
            if result.returncode == 0:
                logging.info(f"挂载成功: {self.device} -> {self.mount_point}")
                return True
            else:
                logging.error(f"挂载失败: {result.stderr}")
                return False
        except Exception as e:
            logging.error(f"挂载错误: {e}")
            return False
    
    def unmount_device(self):
        """卸载设备"""
        try:
            result = subprocess.run(['umount', self.mount_point], 
                                  capture_output=True, text=True)
            if result.returncode == 0:
                logging.info(f"卸载成功: {self.mount_point}")
                return True
            else:
                logging.error(f"卸载失败: {result.stderr}")
                return False
        except Exception as e:
            logging.error(f"卸载错误: {e}")
            return False
    
    def monitor(self):
        """监控循环"""
        last_state = self.check_device()
        logging.info(f"开始监控，初始状态: {'存在' if last_state else '不存在'}")
        
        while self.running:
            current_state = self.check_device()
            
            if current_state != last_state:
                if current_state:
                    logging.info("SD卡插入检测到")
                    time.sleep(2)  # 等待设备稳定
                    self.mount_device()
                else:
                    logging.info("SD卡拔出检测到")
                    self.unmount_device()
                
                last_state = current_state
            
            time.sleep(1)
    
    def start(self):
        """启动监控"""
        self.running = True
        logging.info("启动SD卡监控器")
        
        # 检查当前状态
        if self.check_device():
            logging.info("检测到SD卡已存在，尝试挂载")
            self.mount_device()
        
        # 启动监控线程
        self.monitor_thread = threading.Thread(target=self.monitor, daemon=True)
        self.monitor_thread.start()
    
    def stop(self):
        """停止监控"""
        self.running = False
        logging.info("停止SD卡监控器")
        self.unmount_device()